package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.UserInfo;
import com.scuec.groupfive.service.UserClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/userClient")
public class UserClientController {
    @Autowired
    private UserClientService userClientService;

    // 获取当前登录用户ID的辅助方法
    private Integer getCurrentUserId(HttpServletRequest request) {
        // 这里从请求头中获取用户ID，实际项目中应该从token中解析
        String userIdHeader = request.getHeader("X-User-ID");
        if (userIdHeader == null || userIdHeader.isEmpty()) {
            throw new IllegalArgumentException("未提供用户ID");
        }
        try {
            return Integer.parseInt(userIdHeader);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("用户ID格式错误");
        }
    }

    @GetMapping("/list")
    public List<UserInfo> getUserList() {
        // 管理员才能查看所有用户列表
        // 这里需要添加管理员权限检查
        return userClientService.getUserList();
    }

    @GetMapping("/detail/{userId}")
    public UserInfo getUserById(@PathVariable Integer userId, HttpServletRequest request) {
        Integer currentUserId = getCurrentUserId(request);
        // 检查请求的用户ID是否与当前登录用户ID一致
        if (!currentUserId.equals(userId)) {
            throw new SecurityException("无权查看其他用户信息");
        }
        return userClientService.getUserById(userId);
    }

    @PutMapping("/status")
    public int updateUserStatus(
            @RequestParam Integer userId,
            @RequestParam Integer status,
            HttpServletRequest request) {
        Integer currentUserId = getCurrentUserId(request);
        if (!currentUserId.equals(userId)) {
            throw new SecurityException("无权修改其他用户状态");
        }
        return userClientService.updateUserStatus(userId, status);
    }


    @PutMapping("/update")
    //http://localhost:8080/userClient/update
    public int updateUser(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        Integer currentUserId = getCurrentUserId(request);
        if (!currentUserId.equals(userInfo.getUserId())) {
            throw new SecurityException("无权修改其他用户信息");
        }
        return userClientService.updateUser(userInfo);
    }

    @PostMapping("/insert")
    public int addUser(@RequestBody UserInfo userInfo) {
        // 注册接口不需要权限验证
        return userClientService.addUser(userInfo);
    }

    @DeleteMapping("/delete/{userId}")
    public int deleteUser(@PathVariable Integer userId, HttpServletRequest request) {
        Integer currentUserId = getCurrentUserId(request);
        if (!currentUserId.equals(userId)) {
            throw new SecurityException("无权删除其他用户");
        }
        return userClientService.deleteUser(userId);
    }
}